%%%-------------------------------------------------------------------
%%% @author 1
%%% @copyright (C) 2014, <COMPANY>
%%% @doc
%%% окно диспетчера, где просто показывается информация
%%% @end
%%% Created : 06. сен 2014 17:30
%%%-------------------------------------------------------------------
-module(info_ui).

-include_lib("wx/include/wx.hrl").
-include("definitions.hrl").
%% API
-export([start/2, init/2, stop/0]).

%% constants
-define(GRID, 2).
-define(BUTTON_START, 1).

start(ServerPid, DeviceCount) ->
  register(showState, spawn(info_ui, init, [ServerPid, DeviceCount]))
.

init(ServerPid, DeviceCount) ->
  Wx = wx:new(),
  WxStateFrame = wxFrame:new(Wx, -1, "Состояние"),
  wxFrame:setSize(WxStateFrame, {600, 400}),
  %wxFrame:setTitle(WxStateFrame, lists:concat(erlang:pid_to_list(ServerPid))),
  wxFrame:show(WxStateFrame),
  Grid = initControls(WxStateFrame, DeviceCount),
  initCallbacks(WxStateFrame),
  info_updater:init(self()),

  eventLoop(WxStateFrame, Grid),
  wx:destroy().

initCallbacks(WxStateFrame) ->
  wxFrame:connect(WxStateFrame, close_window).

initControls(WxStateFrame, DeviceCount) ->
  %%Button = wxButton:new(WxStateFrame, ?BUTTON_START, [{label, "SHOW"}, {pos, {30, 30}}, {size, {50, 50}}]),
  Grid = wxGrid:new(WxStateFrame, ?GRID, [{size, {700, 600}}]),
  wxGrid:createGrid(Grid, DeviceCount, 6),
  wxGrid:autoSizeRows(Grid),
  wxGrid:autoSizeColumns(Grid),
  wxGrid:setColSize(Grid, 0, 60), %id
  wxGrid:setColSize(Grid, 1, 60), %тест
  wxGrid:setColSize(Grid, 2, 60), %прибор
  wxGrid:setColSize(Grid, 3, 60), %завершен?
  wxGrid:setColSize(Grid, 4, 60), %падал
  wxGrid:setColSize(Grid, 5, 160), %текущий ответ

  wxGrid:setColLabelValue(Grid, 0, "id"),
  wxGrid:setColLabelValue(Grid, 1, "тест"),
  wxGrid:setColLabelValue(Grid, 2, "прибор"),
  wxGrid:setColLabelValue(Grid, 3, "завершен?"),
  wxGrid:setColLabelValue(Grid, 4, "падений"),
  wxGrid:setColLabelValue(Grid, 5, "процент выполнения"),
  Grid
.

eventLoop(WxStateFrame, Grid) ->
  receive
    {updateGrid, ListStates}
      ->
      %io:format("updateGrid received~n"),
      bindGrid(ListStates, Grid),
      eventLoop(WxStateFrame, Grid)
  ;
    stop ->
      io:format("~ninfo_ui finished~n"),
      wxFrame:close(WxStateFrame);

    #wx{event = #wxClose{}} ->
      info_updater:stop(),
      ok;
    Event ->
      io:format("eventLoop: ~p~n", [Event]),
      eventLoop(WxStateFrame, Grid)
  end.

bindGrid(ListStates, Grid) ->
  foreach(ListStates, Grid, 0),
  wxGrid:refresh(Grid).

foreach([], _, _) -> ok;

foreach([H | T], Grid, N) ->
  CellNumber = get_cellIndex(Grid, H#stateRecord.id, N),
  %io:format("~w~n", [CellNumber]),
  wxGrid:setCellValue(Grid, {CellNumber, 0}, integer_to_list(H#stateRecord.id)),
  wxGrid:setCellValue(Grid, {CellNumber, 1}, integer_to_list(H#stateRecord.testId)),
  wxGrid:setCellValue(Grid, {CellNumber, 2}, integer_to_list(H#stateRecord.deviceId)),
  wxGrid:setCellValue(Grid, {CellNumber, 3}, atom_to_list(H#stateRecord.completed)),
  wxGrid:setCellValue(Grid, {CellNumber, 4}, integer_to_list(H#stateRecord.fails)),
  %wxGrid:setCellValue(Grid, {CellNumber, 5}, lists:concat(H#stateRecord.answer)),
  wxGrid:setCellValue(Grid, {CellNumber, 5}, integer_to_list(length(H#stateRecord.answer))),
  %wxGrid:setCellValue(Grid, {N, 4}, H#stateRecord.answer),
  foreach(T, Grid, N + 1).

get_cellIndex(Grid, StateRecordId, DefaultIndex) ->
  GridRowsCount = wxGrid:getNumberRows(Grid),
  Indexes = [Int || Int <- lists:seq(0, GridRowsCount)],
  List = lists:map(fun(Index) -> getFirstColumnValue(Grid, Index) end, Indexes),
  Predicate = fun({Id, RowNumber}) -> StateRecordId == Id end,
  Filtered = lists:filter(Predicate, List),
  N = case Filtered of
        [] -> DefaultIndex;
        NotEmpty ->
          {_, Row} = hd(NotEmpty),
          Row
      end,
  N.

getFirstColumnValue(Grid, RowNumber) ->
  Id = case wxGrid:getCellValue(Grid, {RowNumber, 0}) of
         [] -> -1;
         List -> list_to_integer(List)
       end,
  {Id, RowNumber}.

stop() ->
  case whereis(showState) of
    undefined ->
      io:format("showState finished~n"),
      ok;
    Pid ->
      Pid ! stop
  end.